package com.supply.dl.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.supply.dl.R;
import com.supply.dl.app.ApiService;
import com.supply.dl.app.AppConfig;
import com.supply.dl.app.adapter.NormalAdapter;
import com.supply.dl.app.adapter.RecyclerViewDivider;
import com.supply.dl.app.adapter.ViewHolder;
import com.supply.dl.app.http.BaseInfo;
import com.supply.dl.app.http.BaseObserver;
import com.supply.dl.app.http.HttpMethod;
import com.supply.dl.app.http.RxSchedulers;
import com.supply.dl.bean.JobAttachBean;
import com.supply.dl.bean.SearchStockBean;
import com.supply.dl.bean.TouliaoAddSheetBean;
import com.supply.dl.bean.TouliaoSheetSavePost;
import com.supply.dl.bean.WorkNotesBean;
import com.supply.dl.utils.BigDecimalUtil;
import com.supply.dl.utils.DateUtils;
import com.supply.dl.utils.DialogUtils;
import com.supply.dl.utils.FilePostUtil;
import com.supply.dl.utils.PictureHelper;
import com.supply.dl.utils.StringUtils;
import com.supply.dl.utils.Utils;
import com.supply.dl.utils.utils.ToastUtil;
import com.supply.dl.view.MaxRecyclerView;
import com.supply.dl.widget.LoadTipFailedLayout;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 新整投料单
 * <p>
 * Author: tian <br>
 * Time: 2018/8/21 10:48
 */
public class CreateFeedSheetActivity extends BaseActivity {

    /**
     * 保存时候的提交对象
     */
    private TouliaoSheetSavePost touliaoSheetSavePost;

    /**
     * oms单号,投料单NO
     */
    private String omsOrderNo, orderId;

    /**
     * 显示的数据对象
     */
    private TouliaoAddSheetBean touliaoSheetDetailBean;

    /**
     * 加载框
     */
    @BindView(R.id.inbound_location_detail_main_loadView)
    LoadTipFailedLayout loadTipFailedLayout;

    /**
     * 保存
     */
    @BindView(R.id.save_tv)
    TextView save_tv;

    /**
     * 保存并过账
     */
    @BindView(R.id.save_gz_tv)
    TextView save_gz_tv;

    /**
     * 基本信息
     */
    @BindView(R.id.msg_ly)
    LinearLayout msg_ly;

    /**
     * 伸缩按钮
     */
    @BindView(R.id.open_hide_img)
    ImageView open_hide_img;

    /**
     * 投料明细列表
     */
    @BindView(R.id.touliao_rc)
    MaxRecyclerView touliao_rc;

    /**
     * 附件列表
     */
    @BindView(R.id.fujian_rc)
    MaxRecyclerView fujian_rc;

    /**
     * 附件数据
     */
    private ArrayList<JobAttachBean> fujianDatas;

    /**
     * 附件适配器
     */
    private NormalAdapter<JobAttachBean> fujianAapter;

    /**
     * 投料数据
     */
    private ArrayList<TouliaoAddSheetBean.TLjob> touliaoDatas;

    /**
     * 投料明细adapter
     */
    private NormalAdapter<TouliaoAddSheetBean.TLjob> touliaoAdapter;

    /**
     * 生产订单编号
     */
    @BindView(R.id.sc_order_no_tv)
    TextView sc_order_no_tv;

    /**
     * 订单状态
     */
    @BindView(R.id.status_tv)
    TextView status_tv;

    /**
     * 生产车间
     */
    @BindView(R.id.sc_cj_tv)
    TextView sc_cj_tv;

    /**
     * 订单时间
     */
    @BindView(R.id.sc_time_tv)
    TextView sc_time_tv;

    /**
     * 生产班次
     */
    @BindView(R.id.sc_banci_tv)
    TextView sc_banci_tv;

    /**
     * 作业记录按钮
     */
    @BindView(R.id.work_info_item_showInventoryStatusTv)
    TextView note_tv;

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_feed_operation_detail;
    }

    @Override
    protected void initView() {
        super.initView();
        showLeftBack();
        setTitleShow("新增投料单");

        setRightHomeClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtil.showToast(CreateFeedSheetActivity.this, "home");
            }
        });

        setRightScanClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtil.showToast(CreateFeedSheetActivity.this, "scan");
                Utils.startScanActivity(CreateFeedSheetActivity.this);
            }
        });

        omsOrderNo = getIntent().getStringExtra("omsOrderNo");
        orderId = getIntent().getStringExtra("orderId");
        addTouliaoSheet();
    }

    /**
     * 新建领料单详情
     */
    private void addTouliaoSheet() {
        if (!StringUtils.isCanUse(omsOrderNo)) {
            Toast.makeText(this, "omsOrderNo不可用", Toast.LENGTH_SHORT).show();
            return;
        }

        ApiService apiService = HttpMethod.getInstance().create(ApiService.class);
        apiService.addTouliaoSheet(omsOrderNo)
                .compose(RxSchedulers.<BaseInfo<TouliaoAddSheetBean>>compose(this))
                .subscribe(new BaseObserver<TouliaoAddSheetBean>(this) {
                    @Override
                    public void onSuccess(BaseInfo<TouliaoAddSheetBean> baseInfo) {
                        if (baseInfo != null && baseInfo.getData() != null) {
                            touliaoSheetDetailBean = baseInfo.getData();
                            fillOrderView();
                            touliaoDatas.clear();
                            touliaoDatas.addAll(baseInfo.getData().getStockPositionList());
                            touliaoAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                    }
                });
    }

    /**
     * 填充订单信息布局
     */
    private void fillOrderView() {
        sc_order_no_tv.setText("生产订单号:" + touliaoSheetDetailBean.getErpOrderNo());
        status_tv.setText(touliaoSheetDetailBean.getOrderStatusName());
        sc_cj_tv.setText(touliaoSheetDetailBean.getProductWorkshopName());
        sc_time_tv.setText(StringUtils.isEmpty(String.valueOf(touliaoSheetDetailBean.getAddTime())) ? ""
                : DateUtils.getSimpleDateTimeByMill(String.valueOf(touliaoSheetDetailBean.getAddTime()), DateUtils.DATE_TIME_FORMAT));//建单时间
        sc_banci_tv.setText("生产班次:" + "");
    }


    @Override
    protected void initRecyclerView() {

        touliaoSheetSavePost = new TouliaoSheetSavePost();
        touliaoSheetSavePost.setJobAmounts(new ArrayList<TouliaoSheetSavePost.WorkNotesPost>());
        touliaoSheetSavePost.setJobAttach(new ArrayList<JobAttachBean>());
        touliaoSheetSavePost.setJobs(new ArrayList<TouliaoSheetSavePost.JobPost>());

        touliaoDatas = new ArrayList<>();
        touliaoAdapter = new NormalAdapter<TouliaoAddSheetBean.TLjob>(this, touliaoDatas) {
            @Override
            protected void convert(ViewHolder holder, final TouliaoAddSheetBean.TLjob data) {

                //库位名字
                holder.setText(R.id.ck_name_tv, "库位名字:" + data.getStockName());
                //物料编码
                holder.setText(R.id.wl_number_tv, "物料编码:" + data.getSkuCode());
                //物料名称
                holder.setText(R.id.wl_name_tv, "物料名称:" + data.getSkuName());
                //库存状态
                holder.setText(R.id.kc_status_tv, "库存状态:" + data.getStockStatusName());

                //库存类型
                holder.setText(R.id.kc_type_tv, "库存类型:" + data.getStockTypeName());

                //规格
                holder.setText(R.id.guige_tv, "规格:" + data.getUnitName());

                //批次号
                holder.setText(R.id.pici_code_tv, "批次号:" + data.getBatchNo());

                //库存信息
                holder.setText(R.id.kc_count_tv, "库存数量:" + data.getAvaiableAmount() + "件," + data.getAvaiableWeight() + "吨,"
                        + data.getAvaiableVolume() + "方");

                final EditText count_jian_et = holder.getView(R.id.count_jian_et);
                final EditText count_dun_et = holder.getView(R.id.count_dun_et);
                final EditText count_fang_et = holder.getView(R.id.count_fang_et);

                //件
                count_jian_et.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        if (StringUtils.isCanUse(s.toString())) {
                            if (data.getAvaiableAmount() == null) {
                                count_jian_et.setText("");
                                count_jian_et.setHint("请勿输入");
                                return;
                            }

                            BigDecimal input = BigDecimalUtil.getBigDecimalByString(s.toString());

                            if (input.compareTo(data.getAvaiableAmount()) <= 0) {
                                data.setAmount(input);

                                save_tv.setText("保存");
                                save_gz_tv.setText("保存并过账");
                            }
                            //
                            else {
                                count_jian_et.setText("");
                                count_jian_et.setHint("输入不能大于库存");
                            }
                        }
                    }
                });

                //吨
                count_dun_et.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        if (StringUtils.isCanUse(s.toString())) {

                            if (data.getAvaiableWeight() == null) {
                                count_dun_et.setText("");
                                count_dun_et.setHint("请勿输入");
                                return;
                            }

                            BigDecimal input = BigDecimalUtil.getBigDecimalByString(s.toString());

                            if (input.compareTo(data.getAvaiableWeight()) <= 0) {
                                data.setWeight(input);
                                save_tv.setText("保存");
                                save_gz_tv.setText("保存并过账");
                            }
                            //
                            else {
                                count_dun_et.setText("");
                                count_dun_et.setHint("输入不能大于库存");
                            }
                        }
                    }
                });

                //方
                count_fang_et.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        if (StringUtils.isCanUse(s.toString())) {

                            if (data.getAvaiableVolume() == null) {
                                count_fang_et.setText("");
                                count_fang_et.setHint("请勿输入");
                                return;
                            }

                            BigDecimal input = BigDecimalUtil.getBigDecimalByString(s.toString());

                            if (input.compareTo(data.getAvaiableVolume()) <= 0) {
                                data.setVolume(input);
                                save_tv.setText("保存");
                                save_gz_tv.setText("保存并过账");
                            }
                            //
                            else {
                                count_fang_et.setText("");
                                count_fang_et.setHint("输入不能大于库存");
                            }
                        }
                    }
                });

                holder.getView(R.id.delete_touliao_img).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        DialogUtils.showDialog(CreateFeedSheetActivity.this, "提示", "确定删除当前投料明细吗?", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                touliaoDatas.remove(data);
                                touliaoAdapter.notifyDataSetChanged();
                            }
                        }).show();
                    }
                });

            }

            @Override
            protected int getItemLayoutId() {
                return R.layout.item_touliao;
            }
        };

        touliao_rc.setLayoutManager(new LinearLayoutManager(this));
        touliao_rc.addItemDecoration(new RecyclerViewDivider(this, LinearLayoutManager.VERTICAL));
        touliao_rc.setAdapter(touliaoAdapter);

        fujianDatas = new ArrayList<>();

        fujianAapter = new NormalAdapter<JobAttachBean>(this, fujianDatas) {
            @Override
            protected void convert(ViewHolder holder, final JobAttachBean data) {
                String[] temp = data.photoPath.split("/");
                holder.setText(R.id.fujian_name_tv, temp[temp.length - 1]);
                holder.getView(R.id.delete_fujian_img).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        DialogUtils.showDialog(CreateFeedSheetActivity.this, "提示", "确定删除当前附件吗?", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                fujianDatas.remove(data);
                                fujianAapter.notifyDataSetChanged();
                                touliaoSheetSavePost.getJobAttach().remove(data);
                            }
                        }).show();
                    }
                });
            }

            @Override
            protected int getItemLayoutId() {
                return R.layout.item_fujian;
            }
        };

        fujian_rc.setLayoutManager(new LinearLayoutManager(this));
        fujian_rc.addItemDecoration(new RecyclerViewDivider(this, LinearLayoutManager.VERTICAL));
        fujian_rc.setAdapter(fujianAapter);

    }

    @OnClick({R.id.save_tv, R.id.save_gz_tv,
            R.id.open_hide_img, R.id.add_fujian_img, R.id.add_touliao_detail_img,
            R.id.work_info_item_showInventoryStatusTv})
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {

            //保存
            case R.id.save_tv:

                if ("已保存".equals(save_tv.getText().toString())) {
                    Toast.makeText(CreateFeedSheetActivity.this, "已保存，无需在保存", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (touliaoSheetSavePost.getJobAttach().size() > 0) {
                    FilePostUtil.postFile(CreateFeedSheetActivity.this, touliaoSheetSavePost.getJobAttach(),
                            new FilePostUtil.OnFilePostEndListener() {
                                @Override
                                public void onFilePostEnd() {
                                    saveTouliao();
                                }
                            });

                    return;
                }

                saveTouliao();
                break;

            //保存并过账
            case R.id.location_lot_tv:

                if ("已过账".equals(save_gz_tv.getText().toString())) {
                    Toast.makeText(CreateFeedSheetActivity.this, "已过账，无需在过账", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (touliaoSheetSavePost.getJobAttach().size() > 0) {
                    FilePostUtil.postFile(CreateFeedSheetActivity.this, touliaoSheetSavePost.getJobAttach(),
                            new FilePostUtil.OnFilePostEndListener() {
                                @Override
                                public void onFilePostEnd() {
                                    passTouliaoBill();
                                }
                            });

                    return;
                }

                passTouliaoBill();

                break;

            //隐藏和显示按钮
            case R.id.open_hide_img:

                if (msg_ly.getVisibility() == View.VISIBLE) {
                    msg_ly.setVisibility(View.GONE);
                    open_hide_img.setBackgroundResource(R.mipmap.icon_down);
                }
                //
                else {
                    msg_ly.setVisibility(View.VISIBLE);
                    open_hide_img.setBackgroundResource(R.mipmap.icon_up);
                }
                break;

            //添加投料明细
            case R.id.add_touliao_detail_img:

                Bundle bundle = new Bundle();
                //物料编码
                bundle.putString("skuId", "");
                //页面名字
                bundle.putString("titleName", "库存选择");
                //仓库id
                bundle.putString("whId", "");

                Intent it = new Intent(CreateFeedSheetActivity.this, DepotSelectActivity.class);
                it.putExtras(bundle);
                startActivityForResult(it, AppConfig.BaseDataAction.REQCODE_CHOOSE_STOCK);

                break;

            //选择附件
            case R.id.add_fujian_img:
                PictureHelper.toSelectPicture(CreateFeedSheetActivity.this);
                break;

            //跳转去 选择作业记录
            case R.id.work_info_item_showInventoryStatusTv:
                Intent intent = new Intent(CreateFeedSheetActivity.this, OperateRemarkActivity.class);
                intent.putExtra("factoryId", "");
                CreateFeedSheetActivity.this.startActivityForResult(intent, AppConfig.BaseDataAction.REQCODE_ADD_OPERATE_REMARK);

                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null)
            return;
        switch (requestCode) {

            //选择库存
            case AppConfig.BaseDataAction.REQCODE_CHOOSE_STOCK:
                if (data.hasExtra("selectBean")) {
                    SearchStockBean selectBean = (SearchStockBean) data.getSerializableExtra("selectBean");

                    TouliaoAddSheetBean.TLjob job = new TouliaoAddSheetBean.TLjob();

                    job.setStockId(selectBean.getStockId());
                    job.setStockName(selectBean.getStockName());
                    job.setSkuCode(selectBean.getSkuCode());
                    job.setSkuId(selectBean.getSkuId());
                    job.setSkuName(selectBean.getSkuName());
                    job.setStockType(selectBean.getStockType());
                    job.setStockTypeName(selectBean.getStockTypeName());
                    job.setStockStatus(selectBean.getStockStatus());
                    job.setStockStatusName(selectBean.getStockStatusName());
                    job.setUnit(selectBean.getUnit());
                    job.setUnitId(selectBean.getUnitId());
                    job.setUnitName(selectBean.getUnitName());
                    job.setBatchNo(selectBean.getBatchNo());
                    job.setInvId(selectBean.getId());
                    job.setWhId(selectBean.getWhId());
                    job.setAvaiableAmount(new BigDecimal(selectBean.getAvailableInventoryPiece()));
                    job.setAvaiableWeight(new BigDecimal(selectBean.getAvailableInventoryTon()));
                    job.setAvaiableVolume(new BigDecimal(selectBean.getAvailableInventorySquare()));

                    job.setPackageWeight(BigDecimalUtil.getBigDecimalByString(selectBean.getPackageWeight()));

                    touliaoDatas.add(job);
                    touliaoAdapter.notifyDataSetChanged();
                }
                break;

            //添加作业记录
            case AppConfig.BaseDataAction.REQCODE_ADD_OPERATE_REMARK:
                ArrayList<WorkNotesBean> remarks = (ArrayList<WorkNotesBean>) data.getSerializableExtra("remarks");

                if (remarks == null || remarks.size() == 0)
                    return;

                note_tv.setText("已填写");

                for (WorkNotesBean wb : remarks) {
                    TouliaoSheetSavePost.WorkNotesPost wnPost = new TouliaoSheetSavePost.WorkNotesPost();

                    /**
                     * 特别注意 这里的 noticeOrderId，noticeOrderNo接口7.1和7.3都没有，目前写死为""
                     */
                    wnPost.noticeOrderId = "";
                    wnPost.noticeOrderNo = "";
                    wnPost.tfJobId = "";
                    wnPost.userIds = wb.getUserIds();
                    wnPost.jobModeIds = wb.getJobModeIds();
                    wnPost.feeIds = wb.getFeeIds();
                    wnPost.departId = wb.getDepartId();
                    wnPost.jobAmout = BigDecimalUtil.getBigDecimalByString(wb.getJobAmount());
                    wnPost.jobWeight = BigDecimalUtil.getBigDecimalByString(wb.getJobWeight());
                    wnPost.jobVolume = BigDecimalUtil.getBigDecimalByString(wb.getJobVolume());
                    wnPost.remark = wb.getRemark();
                    touliaoSheetSavePost.getJobAmounts().add(wnPost);
                }

                break;

            case PictureConfig.CHOOSE_REQUEST:
                // 图片、视频、音频选择结果回调
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                if (selectList == null || selectList.size() == 0)
                    return;

                ArrayList<JobAttachBean> photos = new ArrayList<>();
                for (LocalMedia media : selectList) {
                    JobAttachBean jobAttachBean = new JobAttachBean();
                    jobAttachBean.photoPath = media.getPath();
                    photos.add(jobAttachBean);
                }

                touliaoSheetSavePost.getJobAttach().addAll(photos);

                fujianDatas.clear();
                fujianDatas.addAll(touliaoSheetSavePost.getJobAttach());
                fujianAapter.notifyDataSetChanged();
                break;
        }
    }

    /**
     * 保存投料
     */
    private void saveTouliao() {

        fillJobs();

        ApiService api = HttpMethod.getInstance().create(ApiService.class);
        api.saveTouliao(touliaoSheetSavePost)
                .compose(RxSchedulers.<BaseInfo<String>>compose(this))
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public void onSuccess(BaseInfo<String> baseInfo) {

                        if (baseInfo != null) {
                            save_tv.setText("已保存");
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                    }
                });
    }

    /**
     * 投料过账
     */
    private void passTouliaoBill() {

        fillJobs();

        ApiService api = HttpMethod.getInstance().create(ApiService.class);
        api.passTouliaoBill(touliaoSheetSavePost)
                .compose(RxSchedulers.<BaseInfo<String>>compose(this))
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public void onSuccess(BaseInfo<String> baseInfo) {
                        if (baseInfo != null) {
                            save_gz_tv.setText("已过账");
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                    }
                });

    }

    /**
     * 封装作业明细
     */
    private void fillJobs() {
        for (TouliaoAddSheetBean.TLjob tLjob : touliaoDatas) {
            TouliaoSheetSavePost.JobPost job = new TouliaoSheetSavePost.JobPost();

            job.id = tLjob.getId();
            job.tfOrderId = orderId;
            job.tfOrderNo = touliaoSheetDetailBean.getErpOrderNo();
            job.tfOrderDetailId = "";

            /**
             * 特别注意 这里的 noticeOrderId，noticeOrderNo接口7.1和7.3都没有，目前写死为""
             */
            job.tfNoticeOrderId = "";
            job.tfNoticeOrderNo = "";

            job.stockType = tLjob.getStockType();
            job.stockStatus = tLjob.getStockStatus();
            job.skuId = tLjob.getSkuId();
            job.skuCode = tLjob.getSkuCode();
            job.skuName = tLjob.getSkuName();
            job.tfOutAmount = tLjob.getAmount();
            job.tfOutWeight = tLjob.getWeight();
            job.tfOutVolume = tLjob.getVolume();

            /**
             * 特别注意，生产班次在新增的情况下，写死""
             */
            job.productTeam = "";
            job.packageWeight = tLjob.getPackageWeight();
            job.batchNo = tLjob.getBatchNo();
            job.invId = tLjob.getInvId();
            job.tfOutWhId = tLjob.getWhId();
            job.tfOutStockId = tLjob.getStockId();
            job.unitId = tLjob.getUnitId();
            job.remark = "";

            touliaoSheetSavePost.getJobs().add(job);
        }
    }
}


